package blue.qingyu.whimurmur.enhancement.interceptor;

import java.net.URLDecoder;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import blue.qingyu.whimurmur.enhancement.model.ThumbUp;
import io.jpress.JPressOptions;
import io.jpress.core.addon.annotation.GlobalInterceptor;
import io.jpress.core.template.Template;
import io.jpress.core.template.TemplateManager;

/**
 * @author zhangxr
 * @Title:
 * @Package
 * @Description:
 * @date 2020年8月20日 0020 17:15
 */
@GlobalInterceptor
public class TemplateInterceptorEx implements Interceptor, JPressOptions.OptionChangeListener {

    // 额外使页面可以获取一些常见的setting，原来只能获取网站相关，这里使页面可以获取一些当前模板相关的设置
//    private static String webTitle = null;
//    private static String webSubTitle = null;
//    private static String webName = null;
//    private static String webDomain = null;
//    private static String webCopyright = null;
//    private static String webIpcNo = null;
//    private static String seoTitle = null;
//    private static String seoKeyword = null;
//    private static String seoDescription = null;

    private static String tTitle = null;
    private static String tVersion = null;
    private static String tPath = null;
    private static String jpressVersion = null;
    private static String jpressVersionCode = null;

    public TemplateInterceptorEx(){
//        System.out.println("TemplateInterceptorEx: enter constructor");
        init();
        JPressOptions.addListener(this);
    }

    public void init() {
        Template currentTemplate = TemplateManager.me().getCurrentTemplate();
        tTitle = currentTemplate.getTitle();
        tVersion = currentTemplate.getVersion();
        tPath = currentTemplate.getRelativePath();
        jpressVersion = JPressOptions.get("jpress_version");
        jpressVersionCode = JPressOptions.get("jpress_version_code");
    }

    @Override
    public void intercept(Invocation invocation) {
//        System.out.println("TemplateInterceptorEx: enter intercept");
        Controller controller = invocation.getController();
        controller.setAttr("T_TITLE", tTitle);
        controller.setAttr("T_VERSION", tVersion);
        controller.setAttr("T_PATH", tPath);
        controller.setAttr("JPRESS_VERSION", jpressVersion);
        controller.setAttr("JPRESS_VERSION_CODE", jpressVersionCode);
        
        // 点赞：count#articleId#articleId=userId#-1；末尾-1表示没有点赞，否则对最后一个点赞，最多点赞20次
        String thumbUp = controller.getCookie("thumbUp");
        try {
//	        System.out.println("thumbUp:"+thumbUp);
	        if(null != thumbUp) {// 已初始化
	        	thumbUp = URLDecoder.decode(thumbUp, "UTF-8");
	        	String[] thumbUpArr = thumbUp.split("#");
        		if(Integer.parseInt(thumbUpArr[0]) < 20 && !thumbUpArr[thumbUpArr.length-1].equals("-1")) {
        			String[] articleAndUser = thumbUpArr[thumbUpArr.length-1].split("=");
	        		Long userId = null;
	            	if(articleAndUser.length == 2)//登陆用户点赞
	            		userId = Long.parseLong(articleAndUser[1]);
	            	Long articleId = Long.parseLong(articleAndUser[0]);
	            	incThumbUp(articleId, userId);
	            	// 更新赞数与cookie过期时间
	            	thumbUpArr[0] = String.valueOf(Integer.parseInt(thumbUpArr[0])+1);
	            	controller.setCookie("thumbUp", String.join("#", thumbUpArr)+"#-1", 3600*24 - controller.getCookieObject("thumbUp").getMaxAge());
        		}
	        	
	        }else {// 初始化
	        	// 末尾-1表示没有点赞
	        	controller.setCookie("thumbUp", "0#-1", 3600*24);
	        }
        }catch(Exception e) {
    		Log.getLog(TemplateInterceptorEx.class).warn("错误, 点赞失败", e);
    	};

        invocation.invoke();
    }

    @Override
    public void onChanged(String key, String newValue, String oldValue) {
        switch (key) {
            case "web_template":
//                System.out.println("TemplateInterceptorEx: change web_template");
                Template currentTemplate = TemplateManager.me().getTemplateById(newValue);
                tTitle = currentTemplate.getTitle();
                tVersion = currentTemplate.getVersion();
                tPath = currentTemplate.getRelativePath();
                break;

        }
    }
    
    /**
     * 点赞
     */
    private void incThumbUp(Long articleId, Long userId) {
        if(null != userId){
            int existUser = Db.queryInt("select count(*) from ex_thumb_up_user where user_id = ? and article_id = ?", userId, articleId);
            if(existUser == 1){
                // 已存在该用户的点赞
//                renderJson("code", 1);
                return;
            }
        }

        ThumbUp thumbUp = new ThumbUp().findFirst("select * from ex_thumb_up where article_id = ?", articleId);
        Long thumbUpId = null;
        if(thumbUp != null){
//            System.out.println(thumbUp.toString());
            thumbUpId = thumbUp.getId();
            Long anonymousDayNum = thumbUp.getAnonymousDayNum();
            // 从数据库取出的日期是java.sql.Date
            Date anonymousDay = new Date(thumbUp.getAnonymousDay().getTime());
            if(userId == null){
                LocalDate now = LocalDate.now();
                LocalDate anonymousLocalDate = anonymousDay.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                if(now.equals(anonymousLocalDate)){
                    // 每天最多匿名点赞50次
//                    if(anonymousDayNum >= 50){
//                        renderJson("code", 2);
//                        return;
//                    }else {
                        anonymousDayNum++;
//                    }
                }else {
                    anonymousDayNum = 1l;
                    anonymousDay = Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant());
                }
            }

            thumbUp.setThumbUpNum(thumbUp.getThumbUpNum() + 1);
            thumbUp.setAnonymousDay(anonymousDay);
            thumbUp.setAnonymousDayNum(anonymousDayNum);
            thumbUp.setModified(new Date());
            thumbUp.setModifiedBy(userId == null ? 0 : userId);
            thumbUp.update();

        }else{
            Record record = new Record().set("article_id", articleId)
                    .set("thumb_up_num", 1)
                    .set("anonymous_day_num", userId == null ? 1 : 0)
                    .set("anonymous_day", new Date())
                    .set("created", new Date())
                    .set("created_by", userId == null ? 0 : userId);
            Db.save("ex_thumb_up", record);
            thumbUpId = record.get("id");
        }

        if(userId != null) {
            Record userThumbUpUser = new Record().set("article_id", articleId)
                    .set("user_id", userId)
                    .set("thumb_up_id", thumbUpId);
            Db.save("ex_thumb_up_user", userThumbUpUser);
        }

//        renderJson("code", 0);
    }
}
